<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\facade\Mns;
use app\models\{Region, PlatClass, Banner, Goods, Business, GoodsSpec, Wechat, Config, Pgoods, PgoodsSpec, Porder, PorderGoods, Address, User as Users, Order};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{

    public function pgoods()
    {
        $data = $this->request->get();
        $result = (new Pgoods())->order('sale desc')->field('id,images,title,descs');
        if (!empty($data['title'])) {
            $result = $result->where('title|keywords', 'like', '%' . $data['title'] . '%');
        }
        $result = $result->where(['isdel' => 1, 'isSale' => 1])->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true);
            $results['spec'] = (new PgoodsSpec())->where(['goodid' => $results['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit')->select();
        }
        $this->result($result, 0, '获取成功');
    }

    public function getpgoodsdetail()
    {
        $id  = $this->request->get('id/d', '0');
        $result = (new Pgoods())->where(['id' => $id, 'isdel' => 1])->field('id,title,images,sale,isSale,descs,goodsDesc')->find();
        if ($result) {
            $result['images'] = json_decode($result['images'], true);
            $result['sku'] = 0;
            $spec = (new PgoodsSpec())->where(['goodid' => $result['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock')->select();
            $result['spec'] = $spec;
            foreach ($spec as $specs) {
                $result['sku'] += $specs['stock'];
            }
        }
        $this->result($result, 0, '获取成功');
    }


    public function putporder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'specid' => 'require',
            'addressid' => 'require'
        ], [
            'specid.require' => '规格ID不能为空',
            'addressid.require' => '地址ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['specid'] = json_decode($data['specid'] ?? '', true);
        if (empty($data['specid'])) {
            $this->result([], 1, '规格数据错误');
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息错误存在');
        }
        $order = [
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Porder()),
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'getaddress' => $address['getaddress'],
            'address' => $address['address'],
            'lat' => $address['lat'],
            'lon' => $address['lon'],
            'total' => 0,
            'remark' => $data['remark'] ?? '',
            'paytimes' => date('Y-m-d H:i:s'),
            'total' => 0,
            'status' => 2,
            'ptotal' => 0
        ];
        $ordergoods = [];
        foreach ($data['specid'] as $spec) {
            if (empty($spec['id'])  || empty($spec['number'])) {
                $this->result([], 1, '规格参数错误');
            }
            //查询规格是否存在
            $goodspec = (new PgoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
            if (empty($goodspec)) {
                $this->result([], 1, '规格已下架，请重新提交订单');
            }
            //判断商品是否下架
            $goods = (new Pgoods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            if ($goodspec['stock'] < $spec['number']) {
                $this->result([], 1, '库存不足');
            }
            //查找下面有没有相关服务人员
            $order['ptotal'] += $goodspec['price'] * $spec['number'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'goodsid' => $goods['id'],
                'goodspecid' => $goodspec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'name' => $goodspec['name'],
                'number' =>  $spec['number'],
                'unmit' => $goodspec['unmit'],
                'price' =>   $goodspec['price'],
                'total' => floor($spec['number'] * $goodspec['price'] * 100) / 100
            ];
        }
        $order['total'] = $order['ptotal'];
        if (count($ordergoods) < 1 || count($order) < 1) {
            $this->result([], 1, '结算出错,请重试');
        }
        if ($this->request->user['intergal'] < $order['total']) {
            $this->result([], 1, '积分不足，无法兑换');
        }
        Db::startTrans();
        try {
            (new Users())->MoneyEdit($this->request->user_id, 2, -$order['total'], '兑换商品扣除', $order['ordersn']);
            $id = (new Porder())->insertGetId($order);
            (new PorderGoods())->allowfield(true)->saveAll($ordergoods);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['id' => $id], 0, '下单成功');
    }

    public function porderlist()
    {
        $status = $this->request->get('status/d', '');
        $list = (new Porder())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,ordersn,status,total,created')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $ordergoods = (new PorderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,goodsid,price')->select();
            foreach ($ordergoods as $goods) {
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($list, 0, '获取成功');
    }

    public function porderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Porder())->where('id', $id)->field('payment', true)->find();
        if ($list) {
            $list['status_text'] = $list->status_text;
            $goods = (new PorderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }


    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败');
                }
                $results = $res['regeocode']['addressComponent'];
                $resuls = [
                    "adcode" => $results['adcode'] ?? 0,
                    "province" => $results['province'] ?? '',
                    "city" => $results['city'] ?? '',
                    "district" => $results['district'] ?? '',
                    "street_title" => $results['township'] ?? '',
                    'address' => $res['regeocode']['aois'][0]['name'] ?? ($res['regeocode']['pois']['0']['name'] ?? ""),
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }

    public function others()
    {
        $name = $this->request->get('name', '');
        $result = (new Config())->where('name', $name)->value('value') ?? '';
        $this->result($result, 0, '获取成功');
    }

    //支付回调结果
    public function callback()
    {

        $result = (new Wechat())->callback();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    //取消订单回调结果
    public function callback2()
    {
        $result = (new Wechat())->callback2();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    public function oss()
    {

        if ($this->request->isPost()) {
            $file = request()->file('file');
            if (empty($_FILES['file'])) {
                $this->result([], 1, '参数错误');
            }
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 5, 'ext' => 'jpg,png,gif,jpeg'])
                ->move($path);
            if (!$info) {
                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                $url = url($url, '', '', false);
                $url = "https://" . Env('app.api_url') . $url;
                $this->result($url, 0, '获取成功');
            }
        } else {
            $this->result([], 1, '请求错误');
        }
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function banner()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $business = (new Business())
            ->field('id,title,sendkm,' . $filed)
            ->order('dist asc')
            ->having('dist <= sendkm')
            ->select();
        $businessid = array_column($business->toArray(), 'id') ?? [];
        $businessid[] = 0;
        $result = (new Banner())->where(['business' => $businessid])->field('title,id,business,url')->select();
        $this->result($result, 0, '获取成功');
    }


    public function getopenid()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require'
        ], [
            'mobile.require' => '账号不能为空',
            'code.require' => 'code必须填写',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $business = (new Business())->where('account', $data['mobile'])->find();
        if (empty($business)) {
            $results = ['status' => 1, 'info' => '授权失败,商家不存在'];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $result = $app->oauth->user();
            if ($business['wopenid'] == $result['id']) {
                $res = true;
            } else {
                $res = (new Business())->where('id', $data['id'])->update(['wopenid' => $result['id']]);
            }
            if (!$res) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            $data = [
                'first' => [
                    'value' => '这是一个测试订消息'
                ],
                'keyword1' => [
                    'value' => time()
                ],
                'keyword2' => [
                    'value' =>  date('Y-m-d H:i:s')
                ],
                'keyword3' => [
                    'value' => '张三'
                ],
                'keyword4' => [
                    'value' =>  "北京市东城区老李胡同"
                ],
                'remark' => [
                    'value' => "请尽快配货进行服务喔"
                ]
            ];
            (new Order())->message($result['id'], 'mDgUsTS1E5HZBWcijYhQZMYiROSjA3j8j4XmLVld8ns', $data, config('wechat.')['app_id'], '/');
            $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
            return view(null, ['list' => $results]);
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => $e->getMessage()];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 1, 'info' => '授权失败,请重试'];
        return view(null, ['list' => $results]);
    }
}